// pages/home/createTask/index.ts
import api from '../../../api/api'
import scan from '../../../utils/scanCode'
type scanTaskType = 'task' | 'eqm'

Component({

  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    taskNum: '',
    taskName: '',
    partDrawingNumber: '',
    quantity: '',
    equipmentNumber: '',
    techniqueStaff: '',
    techName: '',
    pVisible: false,
    pText: '',
    pValue: [],
    pTitle: '',
    options1: [],
    options2: [],
  },

  /**
   * 组件的方法列表
   */
  methods: {
    // 扫描二维码
    async scanHandle(e: any) {
      const res: any = await scan.scanCode();
      let type: scanTaskType = e.target.dataset.type;
      if (type == 'task') {
        let { taskNum, taskName, partDrawingNumber, quantity, techniqueStaff } = res
        this.setData({
          taskNum, taskName, partDrawingNumber, quantity, techniqueStaff
        })
      } else if (type == 'eqm') {
        let { equipmentNumber } = res
        this.setData({
          equipmentNumber
        })
      }
      if (res) {
        console.log(res)
      }
    },

    //获取数据字典
    async getDictFindByCode(code: string) {
      const res: any = await api.findByTechNameDictionary(
        [{ target: code }]
      );
      let list = [];
      let option = `${code.toLowerCase()}Options`;
      list = res.data[option];
      return list
    },

    // pick选择器 每一列发生变化时的事件
    async onColumnChange(e: any) {
      console.log('picker pick:', e);
      let { column, value } = e.detail;
      if (column === 0) {
        // 这里可以通过接口调用数据
        let code = value[0];
        let options2 = await this.getDictFindByCode(code);
        this.setData({ options2 });
      }

    },

    // pick选择器 点击确认事件
    onPickerChange(e: any) {
      const { key } = e.currentTarget.dataset;
      const { value, label } = e.detail;
      console.log('picker change:', e.detail);
      this.setData({
        [`${key}Visible`]: false,
        [`${key}Value`]: value,
        [`${key}Text`]: formatValue(label),
        techName: formatValue(label)
      });
      function formatValue(list: Array<string>) {
        if (list.length == 0) {
          wx.showToast({
            title: '数据异常',
            icon: 'error',
            duration: 2000
          })
          return ''
        } else if (list[1] == undefined || list[1] == '') {
          return list[0]
        } else {
          return list.join('-')
        }
      }
    },

    // pick选择器 点击取消事件
    onPickerCancel(e: any) {
      const { key } = e.currentTarget.dataset;
      console.log(e, '取消');
      console.log('picker1 cancel:');
      this.setData({
        [`${key}Visible`]: false,
      });
    },

    // pick选择器 打开选择器的事件
    async onTitlePicker() {
      let options1 = await this.getDictFindByCode("GYMC");
      let options2 = await this.getDictFindByCode(options1[0].value);
      this.setData({ pVisible: true, pTitle: '选择工艺', options1, options2 });
      wx.hideKeyboard({
        complete: res => {
          console.log('hideKeyboard res', res)
        }
      })
    },

    // 生成加工单任务
    async createTechTask() {
      let { taskNum, taskName, partDrawingNumber, quantity, equipmentNumber, techName, techniqueStaff } = this.data;
      let condition = Boolean(taskNum && taskName && partDrawingNumber && quantity && equipmentNumber && techName)
      if (!condition) {
        wx.showToast({
          title: '数据不完整',
          icon: 'error',
          duration: 3000
        })
        return
      }
      let params = { taskNum, techName, equipmentNumber, partDrawingNumber, taskName, taskQuantity: quantity, techniqueStaff }
      const res: any = await api.generateTechnique(params);
      if (res.code == 0) {
        wx.showToast({
          title: '创建任务成功',
          icon: 'success',
          duration: 2000
        })
        // 清空数据
        this.setData({ taskNum: '', techName: '', equipmentNumber: '', partDrawingNumber: '', taskName: '', quantity: '', techniqueStaff: '' })
        // 刷新未完成的加工任务列表
        this.triggerEvent('OK');
      } else if (res.code == 5000) {
        wx.showToast({
          title: res.msg.replace("系统异常:", ""),
          icon: 'none',
          duration: 2000
        })
      } else if (res.code == 4005) {
        wx.showToast({
          title: '任务已结束',
          icon: 'none',
          duration: 2000
        })
      } else if (res.code == 4006) {
        // 交班弹框
        // let { msg } = res;
      } else {
        wx.showToast({
          title: res.data,
          icon: 'none',
          duration: 2000
        })
      }
    }


  },
  // 组件所在页面的生命周期
  pageLifetimes: {
    show: function () {
      // 页面被展示

    }
  }
})